//
//  MZTimeTableViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 20/04/12.
//  Copyright 2012 Mehfile Zainab. All rights reserved.
//

#import "MZTimeTableViewController.h"
#import "MZTimeTable.h"
#import "TimeTableXMLParser.h"

@implementation MZTimeTableViewController
@synthesize spinner;
@synthesize alertView;

@synthesize mzTimeTableArray;

#pragma mark -
#pragma mark View lifecycle

- (void)parseXMLFile {
    
    // get the current date
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init] autorelease];
    [dateFormat setDateFormat:@"MMMM"];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    NSString *currentMonth = [[dateFormat stringFromDate:today] lowercaseString];
    
    NSLog(@"Init the XML parsing with file corresponding to month : %@",currentMonth);
   	NSString *bundle = [[NSBundle mainBundle] pathForResource:currentMonth ofType:@"xml"];
    //NSString *bundle = [[NSBundle mainBundle] pathForResource:@"June" ofType:@"xml"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:bundle];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    
    //Initialize the delegate.
    TimeTableXMLParser *parser = [[TimeTableXMLParser alloc] initXMLDefaultParser:self queriedDate:today];
    
    //Set delegate
    [xmlParser setDelegate:parser];
    
    //Start parsing the XML file.
    BOOL success = [xmlParser parse];
    
    if(success)
        NSLog(@"No Errors");
    else
        NSLog(@"Error when parsing XML file!");
}

- (void)parseAgainXMLFile {
    
    // get the next date
    NSDate *tomorrow = [NSDate dateWithTimeInterval:(24*60*60) sinceDate:[NSDate date]];

    NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init] autorelease];
    [dateFormat setDateFormat:@"MMMM"];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    NSString *currentMonth = [[dateFormat stringFromDate:tomorrow] lowercaseString];
    
    NSLog(@"Init the XML parsing with file corresponding to month : %@",currentMonth);
   	NSString *bundle = [[NSBundle mainBundle] pathForResource:currentMonth ofType:@"xml"];
    //NSString *bundle = [[NSBundle mainBundle] pathForResource:@"June" ofType:@"xml"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:bundle];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    
    //Initialize the delegate.
    TimeTableXMLParser *parser = [[TimeTableXMLParser alloc] initXMLDefaultParser:self queriedDate:tomorrow];
    
    //Set delegate
    [xmlParser setDelegate:parser];
    
    //Start parsing the XML file.
    BOOL success = [xmlParser parse];
    
    if(success)
        NSLog(@"No Errors");
    else
        NSLog(@"Error when parsing XML file!");
}

-(void) startLoading:(id)data  {
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[spinner setCenter:CGPointMake(140, 100)]; 
	
	NSString* messageTitleToUser = @"Mehfile Zainab"; 
	alertView = 
    [[UIAlertView alloc]	initWithTitle:messageTitleToUser 
                               message:@"Chargement..." 
                              delegate:self 
                     cancelButtonTitle:nil
                     otherButtonTitles:nil];
	
	[alertView addSubview:spinner];
	[spinner startAnimating];
	[alertView show]; 
	
	[pool drain];
	
}

-(void) stopLoading  {
	//if you programmatically want to close the alert view 
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	// stop spinner 
	[spinner stopAnimating];
}


- (void)initTimeTable {
	
	[NSThread detachNewThreadSelector:@selector(startLoading:) toTarget:self withObject:nil];
    
    [self parseXMLFile];

    [self parseAgainXMLFile];
    
    [self stopLoading];
    
    /*
	mzTimeTableArray = [[NSMutableArray alloc] init];
	MZTimeTable *timeTable;
	NSMutableArray *timeValues;
	
	timeTable = [[MZTimeTable alloc] init];
	timeValues = [[NSMutableArray alloc] init];
	[timeValues addObject:@"01h00"];
	[timeValues addObject:@"02h00"];
	[timeValues addObject:@"03h00"];
	[timeValues addObject:@"04h00"];
	[timeValues addObject:@"05h00"];
	timeTable.mzNamazDate = @"17 Avril 2012";
	[timeTable setNamazTimeDictionaryWithValuesArray:timeValues];
	
	[mzTimeTableArray addObject:timeTable];
	[timeValues release];
	[timeTable release];

	timeTable = [[MZTimeTable alloc] init];
	timeValues = [[NSMutableArray alloc] init];
	[timeValues addObject:@"06h00"];
	[timeValues addObject:@"07h00"];
	[timeValues addObject:@"08h00"];
	[timeValues addObject:@"09h00"];
	[timeValues addObject:@"10h00"];
	timeTable.mzNamazDate = @"18 Avril 2012";
	[timeTable setNamazTimeDictionaryWithValuesArray:timeValues];
	[mzTimeTableArray addObject:timeTable];
	[timeValues release];
	[timeTable release];
    */
		
}


- (void)viewDidLoad {
    [super viewDidLoad];
	[self initTimeTable];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	return [mzTimeTableArray count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	return [[[mzTimeTableArray objectAtIndex:section] getNamazDefinitionArray] count];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [[mzTimeTableArray objectAtIndex:section] getNamazDate];
}


/*
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	UILabel *sectionHeader = [[[UILabel alloc] initWithFrame:CGRectNull] autorelease];
	sectionHeader.backgroundColor = [UIColor clearColor];
	sectionHeader.textAlignment = UITextAlignmentCenter;
	sectionHeader.font = [UIFont boldSystemFontOfSize:12];
	//sectionHeader.textColor = [UIColor whiteColor];
	sectionHeader.text = [[timeTableArray objectAtIndex:section] objectForKey:nDate];
	return sectionHeader;
}
*/

/*
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	// create the parent view that will hold header Label
	UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 300.0, 18.0)];
	
	// create the button object
	UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
	headerLabel.backgroundColor = [UIColor clearColor];
	headerLabel.opaque = NO;
	headerLabel.textColor = [UIColor blackColor];
	headerLabel.highlightedTextColor = [UIColor whiteColor];
	headerLabel.font = [UIFont boldSystemFontOfSize:16];
	headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 18.0);
	
	// If you want to align the header text as centered
	// headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);
	
	headerLabel.text = [[timeTableArray objectAtIndex:section] objectForKey:nDate];
	[customView addSubview:headerLabel];
	
	return customView;
}
*/

/*
- (CGFloat)tableView:(UITableView *)tableViewheightForHeaderInSection:(NSInteger)section {
	return 40;
} 
*/

/*
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 44.0;
}
*/

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
		
	return 28.0f;
	
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
    }
    
	/*
	NSString *namazName = [namazDefinitionArray objectAtIndex:indexPath.row];
	NSString *namazTime = [[[timeTableArray objectAtIndex:indexPath.section] objectForKey:nTime] objectForKey:namazName];
	*/
	
	NSString *namazName = [[[mzTimeTableArray objectAtIndex:indexPath.section] getNamazDefinitionArray] objectAtIndex:indexPath.row];
	NSString *namazTime = [[[mzTimeTableArray objectAtIndex:indexPath.section] getNamazTimeDictionary] objectForKey:namazName];
	
    // Configure the cell...
    [cell.textLabel setText:namazTime];
    [cell.detailTextLabel setText:namazName];
	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[mzTimeTableArray release];
    [super dealloc];
}


@end

